#include "Djpeg.h"
#include "JPEGDecoder.h"

typedef unsigned long UINT32;
typedef struct _BMP_FILE_HEADER_T{
	UINT8 data0[18];
	UINT8 width[4];
	UINT8 height[4];
	UINT8 data1[28];
}BMP_FILE_HEADER_T;


UINT8 bmp_header[]={
		0x42,0x4D,0x36,0x00,0x90,0x00,0x00,0x00,
		0x00,0x00,0x36,0x00,0x00,0x00,0x28,0x00,
		0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x06,
		0x00,0x00,0x01,0x00,0x18,0x00,0x00,0x00,
		0x00,0x00,0x00,0x00,0x09,0x00,0x00,0x00,
		0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
		0x00,0x00,0x00,0x00,0x00,0x00
};

JPEG_DECODER_T *lp_jpeg_dec1=(JPEG_DECODER_T*)0x800000;
JPEG_DECODER_T *lp_jpeg_dec2=(JPEG_DECODER_T*)0x900000;
unsigned char *jpg=(UINT8*)0x01000000;
unsigned char *bmp=(UINT8*)0x02000000;
BMP_FILE_HEADER_T *g_bmp_header=(BMP_FILE_HEADER_T*)bmp_header;
UINT32 BMPSize;
WORD margin_w=7;

void rgb888_scale(UINT8 *bmp, int w, int h, WORD scale)
{
	int i,j,r,t,n,step=scale;
	UINT8 *src=bmp,*dst=bmp;
	UINT32 R,G,B;
	int len1=(w*3+3)&(~3);
	int len2=(w/scale*3+3)&(~3);

	for (i=0; i<h/scale; i++)
	{
		for (j=0; j<w/scale; j++)
		{
			R=0;
			G=0;
			B=0;
			for (r=0;r<step;r++)
			for (t=0;t<step;t++)
			{
				R+=src[r*len1+j*step*3+t*3+0];
				G+=src[r*len1+j*step*3+t*3+1];
				B+=src[r*len1+j*step*3+t*3+2];
			}
			dst[j*3+0]=R/step/step;
			dst[j*3+1]=G/step/step;
			dst[j*3+2]=B/step/step;
		}
		dst+=len2;
		src+=len1*step;
	}
}

#ifndef _TEST_PATTERN_
int test_jpeg2bmp(UINT32 lp_jpeg_dec)
#else
int c_main()
#endif
{
	int ret;
	JPEG_DECODER_T * jpeg_dec=(JPEG_DECODER_T *)lp_jpeg_dec;
	WORD width,height;
	WORD scale=jpeg_dec->scale;

	jpeg_dec->lpSrcBuf = jpg;
	jpeg_dec->lpDstBuf = bmp+sizeof(BMP_FILE_HEADER_T);
	jpeg_dec->decode_cnt=0;
	jpeg_dec->output_cnt=0;
	ret=JPGDecoder(jpeg_dec);

	if (jpeg_dec->scale_post)
	{
		scale=jpeg_dec->scale_post;
		rgb888_scale(jpeg_dec->lpDstBuf, jpeg_dec->winWidth, jpeg_dec->winHeight, scale);
	}
	width = jpeg_dec->winWidth/scale;
	height = jpeg_dec->winHeight/scale;
	BMPSize=((width*3+3)&(~3))*height;
	g_bmp_header->width[0]=(width>> 0)&0xFF;
	g_bmp_header->width[1]=(width>> 8)&0xFF;
	g_bmp_header->width[2]=(width>>16)&0xFF;
	g_bmp_header->width[3]=(width>>24)&0xFF;
	
	g_bmp_header->height[0]=(height>> 0)&0xFF;
	g_bmp_header->height[1]=(height>> 8)&0xFF;
	g_bmp_header->height[2]=(height>>16)&0xFF;
	g_bmp_header->height[3]=(height>>24)&0xFF;

	*(BMP_FILE_HEADER_T*)bmp=*(BMP_FILE_HEADER_T*)bmp_header;
	BMPSize+=sizeof(BMP_FILE_HEADER_T);

	return ret;
}

